<template>
  <div class="content">
    <Dw_menu/>
    <main class="ml-64 flex-1 p-6 bg-gray-100 min-h-screen">
      <!-- 顶部 Header 区域 -->
      <header class="flex items-center mb-6" style="justify-content: end">
        <div style="width: 64%;">
          <h1 class="text-3xl font-bold text-gray-800">企业招聘管理中心</h1>
          <p class="text-sm text-gray-500 mt-1">
            欢迎回来，{{ DATADWDMK.dwmc + '-' + loginUser.name }}
          </p>
        </div>
        <!-- 右侧用户及通知 -->
        <div class="mx-auto px-4">
          <div class="flex justify-between items-center h-16" style="margin-bottom: 27px;">
            <div class="flex items-center space-x-6">
              <!-- 通知按钮 -->
              <el-popover
                  placement="bottom-end"
                  width="400"
                  v-model="popoverVisible"
                  trigger="click"
                  popper-class="notification-popover"
              >
                <!-- 通知内容列表 -->
                <div class="notification-container">
                  <div class="message-list">
                    <div
                        v-for="(message, index) in currentPageMessages"
                        :key="index"
                        class="message-card"
                        @click="markAsRead(message)"
                    >
                      <el-avatar :size="40" :src="message.YHZP" class="mr-3"></el-avatar>
                      <div class="message-content">
                        <div class="message-header">
                          <span class="sender">{{ message.CFZXM }}</span>
                          <span class="time">{{ formatDate(message.CFSJ) }}</span>
                        </div>
                        <p>{{ message.DZNR }}</p>
                      </div>
                      <div v-if="!message.YDBZ" class="unread-dot"></div>
                    </div>
                  </div>
                  <el-pagination
                      :current-page.sync="currentPage"
                      :page-size="pageSize"
                      :total="messages.length"
                      layout="prev, pager, next"
                      class="pagination"
                      @current-change="handlePageChange"
                  />
                </div>
                <button slot="reference" class="hover:text-slate-600 relative">
                  <i class="el-icon-bell text-xl"></i>
                  <span
                      v-show="(messages.filter(message => message.YDBZ === 0).length) !== 0"
                      class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"
                  ></span>
                </button>
              </el-popover>
              <!-- 用户头像下拉 -->
              <el-dropdown trigger="click">
                <div class="flex items-center cursor-pointer">
                  <el-avatar
                      src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                      class="border-2 hover:text-slate-600"
                  ></el-avatar>
                  <span class="ml-2 hover:text-slate-600">{{ loginUser.name }}</span>
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </div>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item><i class="el-icon-user mr-2"></i>个人中心</el-dropdown-item>
                  <el-dropdown-item><i class="el-icon-setting mr-2"></i>账户设置</el-dropdown-item>
                  <el-dropdown-item divided
                  ><i class="el-icon-switch-button mr-2"></i>退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 原消息按钮 -->
              <button
                  class="hover:text-slate-600 relative"
                  style="display: flex; color: #606266; align-items: center;"
              >
                <i class="el-icon-message text-xl"></i> 消息
              </button>
            </div>
          </div>
        </div>
      </header>

      <!-- 招聘数据概览 -->
      <el-row :gutter="20" class="mb-6">
        <el-col :span="6" v-for="(item, index) in stats" :key="index">
          <el-card shadow="hover" class="stat-card">
            <div class="flex items-center">
              <div :class="`icon-box bg-${item.color}-100`">
                <i :class="`el-icon-${item.icon} text-${item.color}-600`"></i>
              </div>
              <div class="ml-4" >
                <div class="text-sm text-gray-500" @click="goToPageView(item.url)">{{ item.label }}</div>
                <div class="text-2xl font-bold">{{ item.value }}</div>
                <div class="text-xs mt-1" :class="`text-${item.color}-600`">
                  较上周<i :class="item.trend === 'up' ? 'el-icon-top' : 'el-icon-bottom'"></i>
                  {{ item.change }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据可视化区域 -->
      <el-row :gutter="20" class="mb-6">
        <el-col :span="16">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="card-title">职位申请趋势</span>
                <el-select v-model="timeRange" @change="handleTimeRangeChange" size="small" class="w-40">
                  <el-option label="最近7天" :value="true"></el-option>
                  <el-option label="最近30天" :value="false"></el-option>
                </el-select>
              </div>
            </template>
            <!-- 图表容器 -->
            <div ref="chartMain" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="never" class="chart-card">
            <template #header>
              <span class="card-title">职位来源</span>
            </template>
            <!-- 这里添加一个图表容器 柱状统计图，横坐标是岗位名称，纵坐标是该岗位的投递次数 -->
            <div ref="barChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最新投递和系统公告 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="never" class="mb-6">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="card-title">最新投递</span>
                <el-button @click="goToPageViewAllTdData" type="text">查看全部</el-button>
              </div>
            </template>
            <el-table :data="applications" style="width: 100%" :loading="loading">
              <!-- 学生列 -->
              <el-table-column prop="XSXM" label="学生" width="120">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <el-avatar :size="30" :src="row.XSZP" class="mr-2"></el-avatar>
                    {{ row.XSXM }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="GWMC" label="应聘职位" />
              <el-table-column prop="TDSJ" label="投递时间" width="180" sortable>
                <template #default="{ row }">
                  {{ formatDate(row.TDSJ) }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="statusType[getTdzt(row)]" size="small">
                    {{ getTdzt(row) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button type="text" @click="viewResume(row)">查看简历</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never" >
            <template #header>
              <span class="card-title">系统公告</span>
            </template>
            <el-timeline>
              <el-timeline-item
                  v-for="(notice, index) in notices"
                  :key="index"
                  :timestamp="notice.time"
                  placement="top"

              >
                <div class="notice-item" @click="viewNotice(notice)"  style="cursor: pointer;">
                  <div class="font-medium">{{ notice.title }}</div>
                  <div class="text-gray-600 text-sm mt-1">{{ notice.content }}</div>
                  <el-tag size="mini" class="mt-2" :type="notice.type">
                    {{ notice.tag }}
                  </el-tag>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>
      </el-row>
    </main>
  </div>
</template>

<script>
import * as echarts from 'echarts'; // 只保留 echarts 手动初始化
import Dw_menu from "@/components/dw/Dw_menu.vue";
import axios from 'axios';
import _ from "lodash";
export default {
  components: { Dw_menu },
  data() {
    return {
      popoverVisible: false,
      loading: false,
      timeRange: '7d',
      stats: [
        { label: '发布职位', value: 15, icon: 'suitcase', color: 'blue', trend: 'up', change: 12, url: '/dw/job' },
        { label: '收到简历', value: 234, icon: 'document', color: 'green', trend: 'up', change: 8, url: '/dw/sqzmd' },
        { label: '待处理简历', value: 42, icon: 'files', color: 'orange', trend: 'down', change: 5, url: '/dw/sqzmd' },
        { label: '安排面试', value: 68, icon: 'date', color: 'purple', trend: 'up', change: 20, url: '/dw/msap' }
      ],
      applications: null,
      statusType: {
        '待处理': 'warning',
        '待回应': 'warning',
        '待录入': 'warning',
        '待安排面试': 'warning',
        '已录用': 'primary',
        '待定': 'info',
        '已拒绝': 'danger'
      },
      notices: [
        {
          id: 1,
          time: '2024-02-16',
          title: '系统升级通知',
          content: '2月20日0:00-6:00进行系统维护升级',
          type: 'info',
          tag: '系统通知'
        }
      ],
      loginUser: { username: null, name: null },
      DATADWDMK: null,
      messages: [],
      currentPage: 1,
      pageSize: 5,

      isJsSeven: false,
    };
  },
  computed: {
    currentPageMessages() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.messages.slice(start, start + this.pageSize);
    }
  },
  watch: {
    popoverVisible(val) {
      if (!val) {
        // 弹窗被关闭
        console.log('Popover 已关闭')
        this.handlePopoverClosed()
      }
    }
  },
  mounted() {
    // 注册消息监听 & 取用户数据
    this.$socket.subscribe(this.handleSocketMessage);
    this.getLoginUser();
    this.getXtggData();
    // 延迟执行 showTjtData 等 DOM 完全渲染
    this.$nextTick(() => {
      setTimeout(() => {
        this.showTjtData(this.isJsSeven);
      }, 1000); // 100ms 一般够用
    });

    // 一定要等 DOM 完全渲染完再 init
    this.$nextTick(() => {
      setTimeout(() => {
        this.initBarChart();
        window.addEventListener('resize', this.resizeCharts);
      }, 1000); // 100ms 一般够用
    });
  },
  beforeDestroy() {
    // 组件销毁时取消监听并释放图表实例
    this.$socket.unsubscribe(this.handleSocketMessage);
    if (this._chartInstance) {
      this._chartInstance.dispose();
    }

    window.removeEventListener('resize', () => this.barChart.resize());
  },
  methods: {

    resizeCharts() {
      if (this.barChart) {
        this.barChart.resize();
      }
    },


    handleTimeRangeChange(value){
      this.isJsSeven=value;
      // 延迟执行 showTjtData 等 DOM 完全渲染
      this.$nextTick(() => {
        setTimeout(() => {
          this.showTjtData(this.isJsSeven);
        }, 1000); // 100ms 一般够用
      });
    },
    getXtggData(){
      axios.get("/xtggk/getXtggk").then(response => {
        if (response.data.result) {
          let ResData = response.data.data;
          this.notices = [];
          for (let i = 0; i < ResData.length; i++){
            this.notices.push({
              id: ResData[i].ID,
              time: ResData[i].CJSJ,
              title: ResData[i].GGBT,
            //  content: ResData[i].GGNR,
              type: 'info',
              tag: ResData[i].GGLX
            });
          }
        } else {
          console.warn('获取系统公告失败：', response.data.data);
        }
      }).catch(error => {
        console.error('获取系统公告失败：', error);
      });
    },
    handlePopoverClosed() {
      axios.get("/xxdmk/setRead",{
        params: {
          YHM: this.loginUser.username,
          YHSFDM:3
        }
      }).then(response => {
        if (!response.data.result) {
          $.confirm({
            title: '⚠️ 系统崩溃警告',
            content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（灾难性故障）：
                <br><br>
                <code>${response.data.data}</code>
              </div>`,
            type: 'red',
            typeAnimated: true,
            boxWidth: '500px',
            useBootstrap: false, // 更自由的样式控制
            backgroundDismiss: false, // 禁止点击背景关闭
            theme: 'supervan', // 更显眼的主题风格
            buttons: {
              '⚠ 重新尝试': {
                btnClass: 'btn-red',
                action: () => {
                  this.handlePopoverClosed(); // 重新执行
                }
              }
            }
          });
        } else{
          // 设置为已读
          for (let i = 0; i < this.messages.length; i++) {
            this.messages[i].YDBZ = 1;
          }
        }
      }).catch(error => {
        console.log(error);
        $.confirm({
          title: '⚠️ 网络崩溃警告',
          content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（一般性故障）：
                <br><br>
                <code>${error.message}</code>
              </div>`,
          type: 'red',
          typeAnimated: true,
          boxWidth: '500px',
          useBootstrap: false, // 更自由的样式控制
          backgroundDismiss: false, // 禁止点击背景关闭
          theme: 'supervan', // 更显眼的主题风格
          buttons: {
            '⚠ 重新尝试': {
              btnClass: 'btn-red',
              action: () => {
                this.handlePopoverClosed(); // 重新执行
              }
            }
          }
        });
      });
    },
    async initBarChart() {
      this.$nextTick(async () => {
      const el = this.$refs.barChart;
      if (!el) {
        console.error('barChart container not found');
        return;
      }
      // 再次确认容器有宽高
      const { width, height } = el.getBoundingClientRect();
      if (width === 0 || height === 0) {
        console.error(`barChart container has zero size: ${width}×${height}`);
      }

      // 初始化
      this.barChart = echarts.init(el);
        // 示例数据
        const jobStats = [
          /*  { name: '前端工程师', count: 120 },
            { name: '后端工程师', count: 95 },
            { name: '产品经理',   count: 60 },
            { name: 'UI 设计师', count: 45 },
            { name: '测试工程师', count: 30 },*/
        ];
        try {
          const response = await axios.get(
              `/data/getGwtjcsData?YHM=${this.loginUser.username}&YHSFDM=3`
          );
          const resData = response.data;


          if (resData.result && Array.isArray(resData.data)) {
            let data = resData.data;

            for (let i = 0; i < data.length; i++){
              jobStats.push({ name: data[i].GWMC, count: data[i].TDCS });
            }

          } else {
            console.warn('返回数据不是数组：', resData.data);
          }
        } catch (err) {
          console.error('获取统计数据出错：', err);
          return;
        }



      // 配置
      this.barChart.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: jobStats.map(i => i.name),
          axisLabel: { rotate: 30, interval: 0 },
        },
        yAxis: { type: 'value', name: '投递次数' },
        series: [{
          name: '投递次数',
          type: 'bar',
          data: jobStats.map(i => i.count),
          barMaxWidth: '40%',
          label: {
            show: true,               // 👈 开启显示
            position: 'top',          // 👈 数值显示在柱子顶部
            color: '#333',            // 👈 可选：字体颜色
            fontSize: 12              // 👈 可选：字体大小
          },
          itemStyle: {
            color: function (params) {
              const colorList = ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE'];
              return colorList[params.dataIndex % colorList.length];
            }
          }
        }],
      });
      });
    },

    // 异步函数，负责拉取后端统计并渲染 ECharts
    async showTjtData(isJsSeven) {
      this.$nextTick(async () => {
        const dom = this.$refs.chartMain;
        if (!dom) {
          console.warn('图表容器 ref="chartMain" 未找到');
          return;
        }

        // 销毁旧实例
        if (this._chartInstance) {
          this._chartInstance.dispose();
        }


        // 拉取后端统计数据
        let data = [];
        try {
          const response = await axios.get(
              `/data/getTdtjData?YHM=${this.loginUser.username}&YHSFDM=3&JsSeven=${this.isJsSeven? 1 : 0}`
          );
          const resData = response.data;
          if (resData.result && Array.isArray(resData.data)) {
            data = resData.data;
          } else {
            console.warn('返回数据不是数组：', resData.data);
          }
        } catch (err) {
          console.error('获取统计数据出错：', err);
          return;
        }

        // 构建图表数据
        const xData = data.map(item => item.day);
        const yData = data.map(item => item.count);

        // 初始化图表
        this._chartInstance = echarts.init(dom, 'light');
        this._chartInstance.setOption({
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: xData
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: yData,
            type: 'line',
            smooth: true,
            areaStyle: {} // 可选：添加区域图样式
          }]
        });
      });
    },
    formatDate(dateStr) {
      return dateStr ? new Date(dateStr).toLocaleString() : '-';
    },
    // 防抖
    viewNotice: _.debounce(function(notice){
      //跳转到公告详情页面
      this.$router.push({
        path: '/public/PublicXtggView',
        query: { id: notice.id }
      });
    }, 500),
    getTdzt(row) {
      if (row.QRDM === 0) return '待处理';
      else if (row.HYDM === 0) return '待回应';
      else if (row.TDJG === null) return '待录入';
      else {
        switch (row.TDJG) {
          case 0:
            return '不录用';
          case 1:
            return '已录用';
          case 2:
            return '待安排面试';
          case 3:
            return '待定';
        }
      }
    },
    getLoginUser() {
      axios.get('/user/checkSession')
          .then(response => {
            if (response.data.result) {
              this.loginUser.username = response.data.username;
              this.loginUser.name = response.data.name;
              this.getDwYhmDyDw(this.loginUser.username);
              this.getTdData();
              this.getXxdm();
              this.getIndexCount();
            } else {
              this.$message.error('当前用户未登录，请先登录！');
              this.$router.push('/dw/login');
            }
          })
          .catch(console.error);
    },
    getDwYhmDyDw(yhm) {
      axios.get('/dw/getDwDataByDwUserName?dwUserName=' + yhm)
          .then(res => {
            if (res.data.result) {
              this.DATADWDMK = res.data.data;
              // 如果需要更新图表数据，可在此调用：
              // this._chartInstance.setOption({ series: [{ data: 新数据 }] });
            } else {
              this.$message.error('获取单位信息失败！');
            }
          })
          .catch(console.error);
    },
    getTdData() {
      this.loading = true;
      axios.get(`/tdjlk/getTdjlk?Style=4&YHM=${this.loginUser.username}&GWDM=1`)
          .then(res => {
            this.applications = res.data.result ? res.data.data : [];
            if (!res.data.result) {
              this.$message.error('加载投递数据库失败:' + res.data.msg);
            }
            this.loading = false;
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('加载投递数据库失败:' + err.message);
          });
    },
    getXxdm() {
      axios.get(`/xxdmk/getXxdmk?YHM=${this.loginUser.username}&YHSFDM=3`)
          .then(res => {
            if (res.data.result) {
              this.messages = res.data.data.filter(m => m.CFZ !== this.loginUser.username);
            } else {
              this.$message.error('获取消息信息失败:' + res.data.msg);
            }
          })
          .catch(err => {
            this.$message.error('获取消息信息失败:' + err.message);
          });
    },
    getIndexCount() {
      axios.get('/data/getUserIndexCount', {params: {YHM: this.loginUser.username, YHSFDM: 3}})
          .then(res => {
            if (res.data.result) {
              this.stats[0].value = res.data.data.ZWFBS;
              this.stats[1].value = res.data.data.SDJLS;
              this.stats[2].value = res.data.data.DCLJLS;
              this.stats[3].value = res.data.data.APMSS;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(err => {
            this.$message.error('加载数据失败:' + err.message);
          });
    },
    handleSocketMessage(msg) {
      console.log(msg);
    },
    markAsRead(message) {
      message.YDBZ = 1;
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    viewResume(row) {
      // 查看简历逻辑
    },
    goToPageViewAllTdData() {
      this.$router.push('/dw/sqzmd');
    },
    goToPageView(url) {
      this.$router.push(url);
    }
  }
};
</script>

<style scoped>
.icon-box {
  @apply w-12 h-12 rounded-lg flex items-center justify-center;
}

.px-4 {
  padding-left: 0px !important;
}

.stat-card {
  @apply transition-all duration-300 hover:transform hover:scale-105;
}

.chart-card {
  @apply border-0 bg-white rounded-lg shadow-sm;
}

.card-title {
  @apply text-lg font-semibold text-gray-800;
}

.notice-item {
  @apply p-3 bg-gray-50 rounded-lg hover:bg-blue-50 transition-colors;
}

:deep(.el-card__header) {
  @apply border-b-0;
}

/* 消息通知样式 */
.notification-popover {
  padding: 0 !important;
}

.notification-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.message-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.message-content {
  flex: 1;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9em;
  color: #909399;
}

.sender {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
}

.message-content p {
  margin: 0;
  font-size: 1em;
  color: #606266;
}

.unread-dot {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.el-pager li {
  border-radius: 4px;
  transition: background-color 0.2s;
}

.el-pager li:hover {
  background-color: #ecf5ff;
}

.el-pager li.active {
  background-color: #409eff;
  color: #fff;
}


.chart-container {
  width: 100%;
  height: 300px;
}
</style>
